package com.tingyuge.base.thread.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class CountTask extends RecursiveTask<Integer> {


    //阈值
    private static final int THRESHOLD = 5;

    @Override
    protected Integer compute() {
        int sum = 0;
        //如果任务足够小就计算任务
        boolean canCompute = (end-start) <= THRESHOLD;
        if(canCompute){
            System.out.println(Thread.currentThread().getName());
            for (int i = start; i <=end ; i++) {
                sum+=i;

            }
        }else {
            //如果任务大于阈值就切分为俩个任务
            int middle = (start +end ) /2;
          CountTask leftCountTask = new CountTask(start, middle);
            CountTask rightCountTask = new CountTask(middle+1, end);
         /*     //执行子任务
            leftCountTask.fork();
            rightCountTask.fork();*/
            invokeAll(leftCountTask,rightCountTask);
            //等待子任务完成
            int leftResult =  leftCountTask.join();
            int rightResult = rightCountTask.join();
            //合并任务
            sum = leftResult+rightResult;

        }
        return sum;

    }

    private int start;
    private int end;

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool =  new ForkJoinPool(2);
        //生成一个计算任务

        CountTask task = new CountTask(0,100);
//        ForkJoinTask<Integer> submit = forkJoinPool.submit(task);
        Integer invoke = forkJoinPool.invoke(task);


        //抛异常
        if(task.isCompletedAbnormally()){
            System.out.println(task.getException());
        }
        System.out.println(invoke);

    }


}
